package com.freesky.provider.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.freesky.common.dao.entity.Item;
import com.freesky.common.dao.entity.PanelContent;
import com.freesky.common.enums.PanelCategoryEnum;
import com.freesky.common.enums.PanelPositionEnum;
import com.freesky.common.enums.RedisKeyEnum;
import com.freesky.common.enums.ResponseEnum;
import com.freesky.common.exception.EMallException;
import com.freesky.common.exception.MyException;
import com.freesky.common.pojo.PanelCategoryId;
import com.freesky.common.pojo.ZTreeNode;
import com.freesky.common.redis.IRedisTemplate;
import com.freesky.common.utils.reponse.JSONResponse;
import com.freesky.common.utils.reponse.JSONResponseDiretor;
import com.freesky.common.dao.entity.Panel;
import com.freesky.provider.content.service.ICommonService;
import com.freesky.provider.content.service.IHomePanelService;
import com.freesky.provider.content.util.VOUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Freesky
 */
@Service
public class HomePanelServiceImpl implements IHomePanelService {

    private final static Logger log = LoggerFactory.getLogger(HomePanelServiceImpl.class);

    @Autowired
    private IRedisTemplate redisTemplate;

    @Autowired
    private ICommonService commonService;

    @Override
    public List<ZTreeNode> list() {
        List<Panel> panelList = new Panel().selectList(new EntityWrapper().eq("position", PanelPositionEnum.HOME_PAGE).orderBy("sort_order", true));
        ;
        //首页板块
        List<ZTreeNode> list = new ArrayList<>();
        for (Panel panel : panelList) {
            ZTreeNode zTreeNode = VOUtil.changePanelToZTreeNode(panel);
            list.add(zTreeNode);
        }
        return list;
    }

    @Override
    public JSONResponse add(Panel panel) {
        Panel exist = panel.selectOne(new EntityWrapper().eq("name", panel.getName()));
        if (exist != null) {
            throw new MyException(ResponseEnum.PANEL_EXIST_ERROR, null, null);
        }
        panel.setCreated(new Date());
        panel.setUpdated(new Date());
        try {
            panel.insert();
        } catch (Exception e) {
            throw new MyException(ResponseEnum.ADD_PANEL_ERROR, e, null);
        }
        redisTemplate.delete(RedisKeyEnum.HOME_PANEL_CONTENT.getKey());
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse update(Panel panel) {
        panel.setUpdated(new Date());
        try {
            panel.updateById();
        } catch (Exception e) {
            throw new MyException(ResponseEnum.UPDATE_PANEL_ERROR, e, null);
        }
        redisTemplate.delete(RedisKeyEnum.HOME_PANEL_CONTENT.getKey());
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse delete(int id) {
        Panel panel = new Panel();
        panel.setId(id);
        try {
            panel.deleteById();
        } catch (Exception e) {
            throw new MyException(ResponseEnum.DELETE_PANEL_ERROR, e, null);
        }
        redisTemplate.delete(RedisKeyEnum.HOME_PANEL_CONTENT.getKey());
        return JSONResponseDiretor.buildSuccessJSONResponse(null);

    }

    @Override
    public JSONResponse getRecommendPanel() {
        Panel panel = redisTemplate.getCacheObject(RedisKeyEnum.HOME_PANEL_RECOMMEND.getKey(), Panel.class);
        if (panel != null) {
            log.info("读取了推荐板块缓存");
            return JSONResponseDiretor.buildSuccessJSONResponse(panel);
        }

        panel = new Panel().selectOne(new EntityWrapper().eq("position", "ITEM_RECOMMEND"));
        if (panel == null) {
            return JSONResponseDiretor.buildSuccessJSONResponse(null);
        }
        List<PanelContent> contentList = new PanelContent().selectList(new EntityWrapper().eq("panel_id", panel.getId()).orderBy("sort_order", true));
        for (PanelContent content : contentList) {
            if (content.getItemId() != null) {
                Item item = new Item();
                item.setId(content.getItemId());
                item = item.selectById();
                content.setItemName(item.getTitle());
                content.setSalePrice(item.getPrice());
                content.setSubTitle(item.getSellPoint());
                content.setPicUrl(content.getPicUrl());
            }
        }
        panel.setPanelContents(contentList);
        //把结果添加至缓存
        redisTemplate.putCache(RedisKeyEnum.HOME_PANEL_RECOMMEND.getKey(), JSON.toJSON(panel));
        log.info("添加了推荐板块缓存");
        return JSONResponseDiretor.buildSuccessJSONResponse(panel);
    }

    @Override
    public JSONResponse getThanksPanel() {
        List<Panel> list;
        //查询缓存
        list = redisTemplate.getCacheList(RedisKeyEnum.HOME_PANEL_THANK.getKey(), Panel.class);
        log.info("读取了捐赠板块缓存");
        if (list != null) {
            return JSONResponseDiretor.buildSuccessJSONResponse(list);
        }
        list = commonService.getPanelAndContentsById(PanelCategoryId.THANK);
        if (list != null) {
            //把结果添加至缓存
            redisTemplate.putCache(RedisKeyEnum.HOME_PANEL_THANK.getKey(), JSON.toJSON(list));
            log.info("添加了捐赠板块缓存");
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(list);
    }
}
